package mysql

import (
	"errors"
	"time"
	"web_app/models"

	"github.com/jinzhu/gorm"

	"go.uber.org/zap"
)

func CreateComment(c *models.Comment) (err error) {
	comment := models.Comment{
		PostId:    c.PostId,
		ParentId:  c.ParentId,
		CommentId: c.CommentId,
		AuthorId:  c.AuthorId,
		Content:   c.Content,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
	err = db.Table("comment").Create(&comment).Error
	if err != nil {
		zap.L().Error("insert comment failed", zap.Error(err))
		err = errors.New("插入数据失败")
		return
	}
	return
}

func GetCommentListById(id uint64) (commentList []*models.Comment, err error) {
	var count int64
	err = db.Table("comment").
		Where("post_id = ?", id).Count(&count).Error
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
		return
	}
	commentList = make([]*models.Comment, count)
	err = db.Table("comment").Select([]string{"id", "post_id", "comment_id", "author_id", "content", "created_at", "updated_at"}).
		Where("post_id = ?", id).
		Find(&commentList).Error
	//fmt.Println(commentList)
	if gorm.IsRecordNotFoundError(err) {
		err = ErrorInvalidId
		return
	}
	return
}
